package course

import (
	"log"
	"mysqlOp/init/mysql"
	"time"
)

type Course struct {
	Id         int64
	Name       string
	Duration   int
	TeacherID  int64
	Desc       string
	CreateTime time.Time
	UpdateTime time.Time
}

func Insert(c *Course) (*Course, error) {
	if c.CreateTime.IsZero() {
		c.CreateTime = time.Now()
	}
	if c.UpdateTime.IsZero() {
		c.UpdateTime = time.Now()
	}

	sql := "insert into tbl_coures(`name`,duration,teacher_id,`desc`,create_time,update_time) value(?,?,?,?,?,?)"
	res, err := mysql.DB.Exec(sql, c.Name, c.Duration, c.TeacherID, c.Desc, c.CreateTime, c.UpdateTime)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	c.Id, _ = res.LastInsertId()
	return c, nil
}

func GetById(id int) (*Course, error) {
	c := &Course{}
	sql := "select * from tbl_course where id = ?"
	err := mysql.DB.QueryRow(sql, id).Scan(&c.Id, &c.Name, &c.Duration, &c.TeacherID, &c.Desc, &c.CreateTime, &c.UpdateTime)
	return c, err
}

func GetList(maxId int) ([]*Course, error) {
	list := make([]*Course, 0)
	sql := "select * from tbl_course where id < ?"
	rows, err := mysql.DB.Query(sql, maxId)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		c := &Course{}
		err := rows.Scan(&c.Id, &c.Name, &c.Duration, &c.TeacherID, &c.CreateTime, &c.UpdateTime)
		if err != nil {
			log.Println(err)
			return nil, err
		}
		list = append(list, c)
	}
	return list, nil
}

func Update(c *Course) (*Course, error) {
	c.UpdateTime = time.Now()
	sql := "update tbl_course set `name` = ? , duration = ?, teacher_id = ? , `desc` = ?, update_time = ? where id = ?"
	res, err := mysql.DB.Exec(sql, c.Name, c.Duration, c.TeacherID, c.Desc, c.CreateTime, c.UpdateTime)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	_, err = res.RowsAffected()
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return c, nil
}

func Delete(id int64) error {
	sql := "delete from tbl_course where id = ?"
	res, err := mysql.DB.Exec(sql, id)
	if err != nil {
		log.Println(err)
		return err
	}
	_, err = res.RowsAffected()
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func InsertCourseWithTeacher(c *Course, teacherName string) (*Course, error) {
	tx, err := mysql.DB.Begin()
	if err != nil {
		log.Println(err)
		return nil, err
	}
	teacherSql := "insert into tbl_teacher(`name`, create_time,update_time)values(?,?,?)"
	res, err := tx.Exec(teacherSql, teacherName, time.Now(), time.Now())
	if err != nil {
		tx.Rollback()
		log.Println(err)
		return nil, err
	}
	teacherID, _ := res.LastInsertId()
	c.TeacherID = teacherID
	sql := "insert into tbl_course(`name`,duration,teacher_id,`desc`,create_time,update_time)values(?,?,?,?,?,?)"
	res, err = tx.Exec(sql, c.Name, c.Duration, c.TeacherID, c.Desc, c.CreateTime, c.UpdateTime)
	if err != nil {
		tx.Rollback()
		log.Println(err)
		return nil, err
	}
	c.Id, _ = res.LastInsertId()
	tx.Commit()
	return c, nil
}
